<template>
  <div class="inner">
    <div class="right">
      <div class="searchBox">
        <el-form class="demo-form-inline" label-position="left" label-width="100px" @submit.native.prevent>
          <div class="serFlexBox">
            <div class="inputBox">
              <el-row :gutter="12" style="display: flex;flex-wrap: wrap;">
                <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                  <el-form-item label="门店">
                    <el-select @click.native="" v-model="storeId" size="small" style="width: 95%" filterable
                      placeholder="请选择..." popper-class="eloption" @change="selRoleFn">
                      <el-option v-for="item in shopList" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                  <el-form-item label="商品类型">
                    <el-select @change="chekGoogsCategory" v-model="type" style="width: 95%" placeholder="请选择商品类型">
                      <el-option value="0" label="标品" />
                      <el-option value="1" label="非标品" />
                      <el-option value="2" label="自营" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                  <el-form-item label="商品">
                    <el-input v-clearEmoji v-model.trim="sForm.name" style="width: 95%" clearable
                      @keyup.enter.native="searchFn" placeholder="助记符/名称/条码" />
                  </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                  <el-form-item label="商品分类" v-if="type !== '2'">
                    <el-cascader v-if="type === '0'" ref="cascaderRef" @click.native="getCategoryTreeList"
                      v-model.trim="sForm.categoryId" placeholder="请选择商品分类" clearable :props="defaultProps"
                      :options="categoryList" style="width: 95%" filterable @change="handleChange" />
                    <el-select v-if="type === '1'" @click.native="getCategoryList" placeholder="请选择商品分类"
                      v-model="sForm.categoryId" filterable clearable popper-class="eloption" style="width: 95%">
                      <el-option v-for="(val, key) in categoryList1" :key="key" :value="key" :label="val" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                  <el-form-item label="期初数量" v-if="type === '0'">
                    <div style="width: 95%;display: flex;flex-wrap: nowrap;justify-content: space-between;">
                      <el-input v-clearEmoji v-model.number="sForm.minInitial" style="width: 42%" clearable
                        placeholder="" />
                      <span> —— </span>
                      <el-input v-clearEmoji v-model.number="sForm.maxInitial" style="width: 42%" clearable
                        placeholder="" />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :xs="12" :sm="12" :md="12" :lg="8" :xl="6">
                  <el-form-item label="供应商" v-if="type === '0'">
                    <el-select v-model="sForm.supplierId" @click.native="getSCMList" filterable clearable
                      popper-class="eloption" style="width: 95%;" placeholder="请选择">
                      <el-option v-for="shop in firstSupplierList" :key="shop.id" :value="shop.id" :label="shop.name" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            <div class="btnBox">
              <el-button @click.stop="searchFn" class="searchBtn" icon="el-icon-search">搜索</el-button>
              <el-button @click.stop="resetFn" class="resetBtn" icon="el-icon-refresh-right">重置</el-button>
            </div>
          </div>
        </el-form>
      </div>
      <div class="add">
        <el-button class="addBtn" v-has="'storeInventory_export'" @click="exportFn">导出</el-button>
      </div>
      <div class="bottomTable" id="tableBox" v-height>
        <div class="table" style="flex:1;" v-show="type == '0'">
          <vxe-table id="tabe1" v-if="type == '0'" :column-config="{ resizable: true }" border class="tablebox"
            ref="xTable1" :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%"
            height="98%" size="medium" align="center" :footer-method="getSummaries" show-footer>
            <vxe-column type="seq" width="80" title="序号" />
            <vxe-column field="commodityName" title="商品名称"
              :min-width="elTableAdaptationWidth('commodityName', goodsList)" />
            <vxe-column field="firstCode" title="商品条码"
              :min-width="elTableAdaptationWidth('firstCode', goodsList) + 30" />
            <vxe-column field="salesNum" title="销量" min-width="150">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>销量</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                      :class="sort === '2' ? 'iconClsActived' : ''" @click="sortFn('2')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '3' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('3')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="salesVolume" title="销售额" min-width="150">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>销售额</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                      :class="sort === '4' ? 'iconClsActived' : ''" @click="sortFn('4')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '5' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('5')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="stockNum" title="库存数量" min-width="120">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>库存数量</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                      :class="sort === '6' ? 'iconClsActived' : ''" @click="sortFn('6')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '7' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('7')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="initialInventory" title="期初库存数量" width="150" min-width="150">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>期初库存数量</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" :class="sort === '0' ? 'iconClsActived' : ''"
                      class="el-icon-caret-top iconCls" @click="sortFn('0')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '1' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('1')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="storePrice" title="零售价（元）" min-width="150" />
            <vxe-column field="outboundPrice" title="进货价（元）" min-width="150" />
            <vxe-column field="categoryName" title="商品分类"
              :min-width="elTableAdaptationWidth('categoryName', goodsList)" />
            <vxe-column field="unitName" title="单位" width="100" />
            <vxe-column field="inventoryPrice" title="库存总价（元）" min-width="150" />
          </vxe-table>
        </div>
        <div class="table" style="flex:1;" v-show="type == '1'">
          <vxe-table id="tabe2" v-if="type == '1'" :column-config="{ resizable: true }" border class="tablebox"
            ref="xTable2" :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%"
            height="100%" size="medium" align="center" :footer-method="getSummaries" show-footer>
            <vxe-column type="seq" width="80" title="序号" />
            <vxe-column field="commodityName" title="商品名称"
              :min-width="elTableAdaptationWidth('commodityName', goodsList)" />
            <vxe-column field="firstCode" title="商品条码" :min-width="elTableAdaptationWidth('firstCode', goodsList)" />
            <vxe-column field="salesNum" title="销量" min-width="150">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>销量</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                      :class="sort === '2' ? 'iconClsActived' : ''" @click="sortFn('2')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '3' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('3')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="salesVolume" title="销售额" min-width="150">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>销售额</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                      :class="sort === '4' ? 'iconClsActived' : ''" @click="sortFn('4')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '5' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('5')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="stockNum" title="库存重量(KG)" min-width="150">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>库存重量(KG)</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                      :class="sort === '6' ? 'iconClsActived' : ''" @click="sortFn('6')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '7' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('7')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="storePrice" title="零售价（元）" min-width="150" />
            <vxe-column field="outboundPrice" title="进货价（元）" min-width="150" />
            <vxe-column field="categoryName" title="商品分类"
              :min-width="elTableAdaptationWidth('categoryName', goodsList)" />
            <vxe-column field="unitName" title="单位" width="100" />
            <vxe-column field="inventoryPrice" title="库存总价（元）" min-width="150" />
          </vxe-table>
        </div>
        <div class="table" style="flex:1;" v-show="type == '2'">
          <vxe-table id="tabe2" v-if="type == '2'" :column-config="{ resizable: true }" border class="tablebox"
            ref="xTable3" :row-config="{ isHover: true }" :scroll-y="{ enabled: true, gt: 21 }" style="width: 100%"
            height="550" size="medium" align="center" :footer-method="getSummaries" show-footer>
            <vxe-column type="seq" width="80" title="序号" />
            <vxe-column field="commodityName" title="商品名称" />
            <vxe-column field="firstCode" title="商品条码" />
            <vxe-column field="salesNum" title="销量">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>销量</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                      :class="sort === '2' ? 'iconClsActived' : ''" @click="sortFn('2')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '3' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('3')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="salesVolume" title="销售额">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>销售额</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                      :class="sort === '4' ? 'iconClsActived' : ''" @click="sortFn('4')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '5' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('5')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="stockNum" title="库存数量">
              <template #header="{ column }">
                <div style="display: flex;justify-content: center;">
                  <span>库存数量</span>
                  <span style="display: flex;flex-direction: column;">
                    <i style="cursor: pointer;" class="el-icon-caret-top iconCls"
                      :class="sort === '6' ? 'iconClsActived' : ''" @click="sortFn('6')"></i>
                    <i style="cursor: pointer;transform: translateY(-5px);"
                      :class="sort === '7' ? 'iconClsActived' : ''" class="el-icon-caret-bottom iconCls"
                      @click="sortFn('7')"></i>
                  </span>
                </div>
              </template>
            </vxe-column>
            <vxe-column field="storePrice" title="零售价" width="80" />
            <vxe-column field="outboundPrice" title="进货价" width="80" />
            <vxe-column field="inventoryPrice" title="库存总价" />
          </vxe-table>
        </div>
        <div style="padding-top: .1042rem; height: .2604rem;">
          <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
            layout="total, ->,sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import FileSaver from 'file-saver'
import { getSelectStoreGoodsInventoryLogs, getShopEasy, exportStoreGoods } from '@/api/shop'
import { getAllSupplier } from '@/api/report'
import { getDictValueAndNameSource } from "@/api/dictionary";
import { getCategoryTreeList } from "@/api/goods";
export default {
  name: "BuiltInRole",
  data() {
    return {
      roleList: [],
      isActive: "",
      isSearch: false,
      goodsList: [],
      deptList: [],
      deptId: "",
      code: "0",
      nameList: [],
      // nameId: '',
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      defaultProps: {
        children: "children",
        label: "name",
        emitPath: false,
        value: "id",
        checkStrictly: true,
      },
      shopList: [], // 商品分类列表
      type: '0',
      categoryList: [],
      firstSupplierList: [],
      sForm: {
        name: '',
        categoryId: '',
        supplierId: '',
        minInitial: '',
        maxInitial: '',
        level: '',
      },
      sort: '7',
      storeId: '',
      categoryList1: {},
      filterText: '',
      allDataArr: [],
      fieldSort: ['seq', 'commodityName', 'firstCode', 'salesNum', 'salesVolume', 'stockNum', 'initialInventory', 'storePrice', 'outboundPrice', 'categoryName', 'unitName', 'inventoryPrice'],
      allCountObj: {}
    };
  },
  created() {
    this.getShopEasy();
    this.getSCMList();
    // this.getCategoryList();
    // this.getCategoryTreeList();
  },
  methods: {
    selRoleFn() {
      // 切换门店
      this.page.pageNum = 1
      this.getGoodsList()
      // this.getGoodsList()

    },
    async getSCMList() {
      const res = await getAllSupplier();
      if (res.code === 200) {
        const data = res.data;
        this.firstSupplierList = data;
      }
    },
    async getCategoryList() {
      const res = await getDictValueAndNameSource("NONSTANDARD_CATEGORY");
      this.categoryList1 = res.data;
      console.log(this.categoryList1, "this.categoryList");
    },
    async getCategoryTreeList() {
      const res = await getCategoryTreeList();
      if (res.code === 200) {
        this.categoryList = res.data.categoryList;
        console.log("categoryList", this.categoryList);
      }
    },
    chekGoogsCategory() {
      this.sForm.categoryId = ''
      this.page.pageNum = 1
      console.log('type', this.type);
      if (this.type === '0') {
        this.fieldSort = ['seq', 'commodityName', 'firstCode', 'salesNum', 'salesVolume', 'stockNum', 'initialInventory', 'storePrice', 'outboundPrice', 'categoryName', 'unitName', 'inventoryPrice']
      } else if (this.type === '1') {
        this.fieldSort = ['seq', 'commodityName', 'firstCode', 'salesNum', 'salesVolume', 'stockNum', 'storePrice', 'outboundPrice', 'categoryName', 'unitName', 'inventoryPrice']
      } else if (this.type === '2') {
        this.fieldSort = ['seq', 'commodityName', 'firstCode', 'salesNum', 'salesVolume', 'stockNum', 'storePrice', 'outboundPrice', 'inventoryPrice']
      }
      this.getGoodsList()
    },
    async getGoodsList() {
      if (!this.isSearch) {
        this.sForm = {
          name: '',
          categoryId: '',
          supplierId: '',
          minInitial: '',
          maxInitial: '',
          level: ''
        }
      }
      const res = await getSelectStoreGoodsInventoryLogs({
        ...this.sForm,
        type: this.type,
        ...this.page,
        storeId: this.storeId,
        sort: this.sort
      })
      if (res.code === 200) {
        console.log('列表', res.data);
        this.goodsList = res.data.pageInfo.list;
        this.page.total = res.data.pageInfo.total;
        this.allCountObj = {
          initialInventory: res.data.totalInitial ? res.data.totalInitial : 0,
          inventoryPrice: res.data.totalInventoryPrice ? res.data.totalInventoryPrice : 0,
          salesNum: res.data.totalSales ? res.data.totalSales : 0,
          stockNum: res.data.totalStock ? res.data.totalStock : 0,
          salesVolume: res.data.totalVolume ? res.data.totalVolume : 0,
        }
        let $table = null
        if (this.type === '0') {
          $table = this.$refs.xTable1
        } else if (this.type === '1') {
          $table = this.$refs.xTable2
        } else if (this.type === '2') {
          $table = this.$refs.xTable3
        }
        this.getAllCount()
        $table.loadData(this.goodsList);
      }
    },
    searchFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.isSearch = true;
      this.getGoodsList();
    },
    resetFn() {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.sForm = {
        name: '',
        categoryId: '',
        supplierId: '',
        minInitial: '',
        maxInitial: '',
        level: '',
      }
      this.sort = '7'
      this.type = '0'
      this.fieldSort = ['seq', 'commodityName', 'firstCode', 'salesNum', 'salesVolume', 'stockNum', 'initialInventory', 'storePrice', 'outboundPrice', 'categoryName', 'unitName', 'inventoryPrice']
      this.isSearch = false;
      this.getGoodsList();
    },
    async getShopEasy() {
      const res = await getShopEasy();
      if (res.code === 200) {
        console.log('门店', res.data.store);
        this.shopList = res.data.store;
        this.storeId = this.shopList[0].id;
        console.log('this.sForm.storeId', this.sForm.storeId);
        this.getGoodsList()
      }
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getGoodsList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.getGoodsList();
    },
    // 分类选择后
    handleChange(value) {
      console.log("分类", value);
      const nodes = this.$refs.cascaderRef.getCheckedNodes();
      console.log("nodes", nodes);
      this.sForm.categoryId = value;
      this.sForm.level = nodes[0].level;

    },
    sortFn(val) {
      console.log('val', val);
      this.sort = val
      this.getGoodsList();
    },
    getSummaries() {
      return this.allDataArr;
    },
    // 查分账合计
    async getAllCount() {
      let resArr = [];
      this.allDataArr = [];
      this.fieldSort.forEach(e => {
        if (e == 'seq') {
          resArr.push('合计');
        } else if (this.allCountObj[e] == null) {
          resArr.push('-');
        } else {
          resArr.push(this.allCountObj[e]);
        }
      });
      this.allDataArr.push(resArr);
      console.log('this.allDataArr', this.allDataArr);
    },
    async exportFn() {
      this.$confirm('确认导出数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (!this.isSearch) {
          this.sForm = {
            name: '',
            categoryId: '',
            supplierId: '',
            minInitial: '',
            maxInitial: '',
            level: '',
          }
        }
        const response = await exportStoreGoods({
          ...this.sForm,
          type: this.type,
          ...this.page,
          storeId: this.storeId,
          sort: this.sort
        })
        let res = null;
        if (response.data.type === "application/json") {
          const reader = new FileReader();  //创建一个FileReader实例
          reader.readAsText(response.data, 'utf-8'); //读取文件,结果用字符串形式表示
          reader.onload = () => {//读取完成后,**获取reader.result**
            res = JSON.parse(reader.result)
            if (res.code !== 200) {
              this.$message.error(res.message);
              return;
            }
          }
        } else {
          const fileName = decodeURIComponent(response.headers["content-disposition"].split(";")[1].split("''")[1]);
          FileSaver.saveAs(response.data, fileName);
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
.iconCls:hover {
  color: #ee2b08 !important;
}

.iconClsActived {
  color: #ee2b08 !important;
}

.inner {
  display: flex;
  height: 100%;

  .left {
    width: 1.5833rem;
    padding: .1667rem;
    height: 100%;
    border-right: .0052rem solid #e7e7e7;

    .tree {
      width: 1.25rem;
      height: 90%;
      margin: 0;
      padding: 0;
      padding-top: .1042rem;
      overflow-y: auto;

      .liStyle {
        padding: 0 .1042rem;
        cursor: pointer;
        list-style-type: none;
        height: .2344rem;
        line-height: .2344rem;
        text-align: center;
        font-size: .1042rem;
        font-weight: 700;
      }

      .active {
        background-color: #0052d9;
        color: #fff;
      }
    }
  }

  .right {
    padding: .1667rem;
    height: 100%;
    // width: 100%;
    flex: 1;
    width: 100%;
    display: flex;
    flex-direction: column;

    .bottomTable {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
  }
}
</style>
